package com.nhim.cms.admin.client.eldf.ui;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.nhim.cms.admin.shared.EElementType;
import com.nhim.cms.admin.shared.ElementDefinitionProxy;

public class ElementType extends Composite implements IElementType {

	private static ElementTypeUiBinder uiBinder = GWT
			.create(ElementTypeUiBinder.class);

	interface ElementTypeUiBinder extends UiBinder<Widget, ElementType> {
	}

	Map<String, Integer> indexDict = new HashMap<String, Integer>();

	@UiField
	SimplePanel elementTypeContent;
	@UiField
	ListBox elementType;
	IElementType currentWidget;
	
	

	public ElementType() {
		initWidget(uiBinder.createAndBindUi(this));
		createElementType();
	}

	private void createElementType() {
		elementType.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				createInputType(EElementType.valueOf(elementType
						.getValue(elementType.getSelectedIndex())));

			}
		});

		elementType.addItem("TextBox", EElementType.TEXTBOX.toString());
		elementType.addItem("Text Area", EElementType.TEXTAREA.toString());

		for (int i = 0; i < elementType.getItemCount(); i++)
			indexDict.put(elementType.getValue(i), i);

	}

	private void createInputType(EElementType type) {
		switch (type) {
		case TEXTBOX: {
			if (currentWidget != null) {
				elementTypeContent.remove((Widget) currentWidget);
			}
			currentWidget = new ElementTypeTextBox();
			elementTypeContent.add((Widget) currentWidget);
		}
			break;
		case TEXTAREA: {
			if (currentWidget != null) {
				elementTypeContent.remove((Widget) currentWidget);
			}
			currentWidget = new ElementTypeTextArea();
			elementTypeContent.add((Widget) currentWidget);

		}
			break;
		default:
			break;
		}
	}

	public List<String> validate() {
		return currentWidget.validate();
	}

	public void save(ElementDefinitionProxy element) {
		element.setElementType(elementType.getValue(elementType
				.getSelectedIndex()));
		 currentWidget.save(element);
	}

	private void setInputType(EElementType eElementType) {
		createInputType(eElementType);
	}

	public void setData(ElementDefinitionProxy element) {
		if (element != null) {
			elementType
					.setSelectedIndex(indexDict.get(element.getElementType()));
			setInputType(EElementType.valueOf(element.getElementType()));
			currentWidget.setData(element);
		} else {
			setInputType(EElementType.TEXTBOX);
			currentWidget.setData(null);
		}

	}

	


}
